<template>
    <div class="deviceediting">
        <div class="con">
            <!--伸缩 -->
            <div :class="['telescoping', { 'icon-active': !treeflag }]" @click="treeflag = !treeflag">
                <!-- <i class="el-icon-arrow-left" v-show="treeflag"></i> -->
                <!-- <i class="el-icon-arrow-right" v-show="!treeflag"></i> -->
                <el-icon v-show="treeflag"><ArrowLeftBold /></el-icon>
                <el-icon v-show="!treeflag"><ArrowRightBold /></el-icon>
            </div>
            <div :class="['left-tree', { 'left-tree-active': !treeflag }]">
                <div class="mytitle" style="margin-top:0px;margin-bottom:12px">
                    <span style="display: inline-block;width: 3px;height: 18px;background-color: #2178F1; margin-left: 12px; margin-right: 6px;border-radius: 3px;"></span>
                    通道列表
                </div>
                <el-scrollbar style="height:calc(100% - 70px);width: 100%;">
                    <div :class="['left-item', {'active':nowLeftRow.channel_name == item.channel_name}]" v-for="item in leftData" :key="item.channel_id" @click="nowLeftRow = item;leftRowfn()">
                         <img src="../assets/leftmenu/caiji3.png" alt="" v-if="nowLeftRow.channel_name == item.channel_name"><img src="../assets/leftmenu/caiji.png" alt="" v-else><span>{{item.channel_name}}</span>
                    </div>
                </el-scrollbar>
            </div>
            <div  :class="['right-con', { 'right-tab-active': !treeflag }]">
                <div class="top-search">
                    <div class="search-item">
                                <div class="in-item">
                                    <span class="item-name">设备名称</span>
                                    <el-input v-model="search.device_name"  />
                                </div>
                                <div class="in-item">
                                    <span class="item-name">设备地址</span>
                                    <el-input v-model="search.device_address"  />
                                </div>
                                <div class="in-item">
                                    <span class="item-name">扩展地址</span>
                                    <el-input v-model="search.device_addressex"  />
                                </div>

                            <div class="bottomoperate-btn solidcolor" @click="searchFN">搜索</div>
                            <div class="bottomoperate-btn bordercolor" @click="chongzhifn">重置</div>
                    </div>
                     <input  type="file" ref="EXCELinput" accept=".xlsx,.xls"  @change="importTemplateEXCELinput"  style="display: none">
                    <div class="mytitle" style="display: flex;align-items: center;justify-content: space-between;">
                        <div class="leftspan"><span></span>设备列表</div>
                        <div>
                            <el-button type="primary"  @click="ExportTemplateEXCEL">导出设备</el-button>
                            <el-button type="primary"  @click="daoruEXCELmoban" v-show="nowLeftRow.channel_name != '全部设备'">导入设备</el-button>
                        </div>
                    </div>
                </div>
                <div class="mi-table">
                      <el-table :data="leftTable" height="100%" stripe  style="width: 100%;" @selection-change="handleSelectionChange">
                                        <el-table-column type="index" width="55" align="center" label="序号"> </el-table-column>
                                        <el-table-column type="selection" width="55" align="center"> </el-table-column>
                                        <el-table-column prop="device_number"  width="80" label="设备号" align="center"> </el-table-column>
                                        <el-table-column prop="device_name"  width="120" label="设备名称"> </el-table-column>
                                        <el-table-column prop="device_address" width="120" label="设备地址"> </el-table-column>
                                        <el-table-column prop="device_addressex" width="120" label="扩展地址"> </el-table-column>
                                        <el-table-column prop="device_group_name" width="90" label="设备组"> </el-table-column>
                                        <el-table-column prop="device_template_name" width="180" label="设备模板"> </el-table-column>
                                        <el-table-column prop="device_serial_type_name" width="120" label="系列类型"> </el-table-column>
                                        <el-table-column prop="device_protocol_name" width="180" label="通讯协议"> </el-table-column>
                                        <el-table-column prop="break_count" width="90" label="中断次数"> </el-table-column>
                                        <el-table-column prop="resend_count" width="90" label="重发次数"> </el-table-column>
                                        <el-table-column  width="90" label="是否投运" align="center"> 
                                            <template #default="{row}">
                                                    <div class="mysort">
                                                        {{row.run ? '是' :'否'}}
                                                    </div>
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="mqtt" width="90" label="MQTT设备">
                                            <template #default="{row}">
                                                    <div class="mysort">
                                                        {{row.mqtt == 1 ? '是' :'否'}}
                                                    </div>
                                            </template>
                                         </el-table-column>
                                     
                                        <el-table-column  width="180" label="操作" fixed="right" align="center"> 
                                             <template #default="{row}">
                                                    <div class="mysort">
                                                        <el-tooltip class="item" effect="dark" content="编辑" placement="top">
                                                             <img src="../assets/btnImg/edit2.png" alt="" style="margin:0px 26px" @click="editDevice(row)">
                                                        </el-tooltip>
                                                        <el-tooltip class="item" effect="dark" content="删除" placement="top">
                                                          <img src="../assets/btnImg/del2.png" alt="" @click="delDioFN(row)">
                                                        </el-tooltip>  
                                                    </div>
                                                </template>
                                        </el-table-column>
                      </el-table>
                </div>
                <div class="bot-btn">
                     <el-scrollbar style="height:calc(100%);width: 100%;">
                           <div class="scr-div">
                            <div class="left-btn">
                                <div class="btn-item add-btn" @click="addDecivefn">新增设备 <img src="../assets/btnImg/addbtn.png"></div>
                                <div class="btn-item add-btn" style="margin-left:12px" @click="mordaddDecivefn">批量新增设备 <img src="../assets/btnImg/addbtn.png"></div>
                                <div class="btn-item qi-btn" style="margin:0px 12px" @click="editMordfn">批量修改 <img src="../assets/btnImg/editbtn.png"></div>
                                <!-- <div class="btn-item qi-btn" >批量导入 <img src="../assets/btnImg/daoru.png"></div> -->
                                <!-- <div class="btn-item qi-btn" style="margin:0px 12px">批量导出 <img src="../assets/btnImg/daochu.png"></div> -->
                                <div class="btn-item del-btn" @click="delMordfn">批量删除 <img src="../assets/btnImg/del2.png"></div>
                            </div>
                            <div class="right-paging">
                                <el-pagination @size-change="handleSizeChangejiao" @current-change="handleCurrentChangejiao" background
                                        :current-page="currentPage" :page-sizes="[50]" :page-size="50"
                                        layout="total, sizes, prev, pager, next" :total="total">
                                </el-pagination>
                            </div>
                           </div>
                      </el-scrollbar>
                </div>
            </div>
          <el-drawer  v-model="adddrawer" size='580px' direction="rtl" :withHeader='false'>
            <div class="drawer-con">
                 <div class="drawer-top">
                      <span>设备变量</span>
                      <i class="el-dialog__close el-icon el-icon-close" @click="adddrawer = false"></i>
                 </div>
                 <div class="drawer-middle">
                     <!-- <el-scrollbar style="height:100%;width: 100%;"> -->
                         <el-table :data="drawTable" height="100%" stripe  style="width: 100%;" >
                                         <el-table-column type="selection" width="55" align="center"> </el-table-column>
                                        <el-table-column type="index"  width="60" label="序号" align="center"> </el-table-column>
                                        <el-table-column prop="name"   label="变量名称"> </el-table-column>
                                        <el-table-column prop="shuju"  label="所属数据区"> </el-table-column>
                                        <el-table-column prop="shujutype" width="120" label="数据类型">
                                              <template #default="{row}">
                                                    <div>
                                                         <el-select v-model="row.data_type" placeholder="请选择" style="width:90px">
                                                                <el-option
                                                                v-for="item in optionsType"
                                                                :key="item.value"
                                                                :label="item.name"
                                                                :value="item.value">
                                                                </el-option>
                                                        </el-select>
                                                    </div>
                                                </template>
                                        </el-table-column>
                                        <el-table-column prop="id" width="50" label="ID"> </el-table-column>
                                        <el-table-column prop="xishu" width="70" label="转换系数"> </el-table-column>   
                        </el-table>
                    <!-- </el-scrollbar> -->
                 </div>
                 <div class="btn-item qi-btn" style="width:108px;margin-left:20px" @click="versioningvalue = true">批量修改系数 <img src="../assets/btnImg/editbtn.png"></div>
                 <!-- <div class="drawer-bottom">
                    <div class="mybtns">创建</div>
                    <div class="mybtns chongzhi" @click="adddrawer = false">取消</div>
                 </div> -->
            </div>
          </el-drawer>
          <!-- 批量新增设备 -->
          <el-dialog width="700px" draggable  title="批量新增设备" :close-on-click-modal='false' v-model="addMord">
                    <div class="leftandrightdialog leftandrightdialog2 leftandrightdialog3">
                            <div class="items">
                                    <div class="leftname">设备名称 =</div>
                                    <el-input v-model="MorddeviceInfo.prefix"></el-input>
                                    <div class="mytip">(前缀)</div>
                                    <div class="myjia">+</div>
                                    <el-input v-model="MorddeviceInfo.startNumber" style="width:60px;min-width:60px"></el-input>
                                    <div class="mytip">(起始编号)</div>
                                    <div class="myjia">+</div>
                                    <el-input v-model="MorddeviceInfo.suffix" style="width:120px;min-width:120px"></el-input>
                                    <div class="mytip">(后缀)</div>
                            </div>
                            <div class="items">
                                    <div class="leftname">设备个数：</div>
                                    <el-input v-model="MorddeviceInfo.number"></el-input>
                            </div>
                            <div class="items">
                                    <div class="leftname">设备起始地址：</div>
                                    <el-input v-model="MorddeviceInfo.device_address" ></el-input>
                            </div>
                            <div class="items">
                                    <div class="leftname">设备扩展地址：</div>
                                    <el-input v-model="MorddeviceInfo.device_addressex" ></el-input>
                            </div>
                           <div class="items">
                                    <div class="leftname">设备组：</div>
                                    <el-select v-model="deviceInfo.device_group" placeholder="设备组" @change="getDeviceMuban(deviceInfo.device_group,'手动')">
                                                <el-option
                                                v-for="item in deviceGroupList"
                                                :key="item.id"
                                                :label="item.channelName"
                                                :value="item.id">
                                                </el-option>
                                    </el-select>
                            </div>
                            <div class="items">
                                    <div class="leftname">设备子模板：</div>
                                    <el-select v-model="deviceInfo.device_template" placeholder="设备子模板" @change="getDeviceTempSerialList(deviceInfo.device_template,'手动')">
                                                <el-option
                                                v-for="item in deviceTemList"
                                                :key="item.id"
                                                :label="item.channelName"
                                                :value="item.id">
                                                </el-option>
                                        </el-select>
                            </div>
                            <div class="items">
                                    <div class="leftname">设备子系列：</div>
                                   <el-select v-model="deviceInfo.device_serial_type" placeholder="设备子系列">
                                                <el-option
                                                v-for="item in deviceSubSeriesList"
                                                :key="item.id"
                                                :label="item.serial_name"
                                                :value="item.id">
                                                </el-option>
                                        </el-select>
                            </div>
                            <div class="items">
                                    <div class="leftname">通讯协议：</div>
                                       <el-select v-model="MorddeviceInfo.device_protocol" clearable>
                                                <el-option
                                                v-for="item in thoroughfareOptionStatute"
                                                :key="item.id"
                                                :label="item.protocol_alias == '' ? item.name : item.protocol_alias"
                                                :value="item.id">
                                                </el-option>
                                        </el-select>
                            </div>
                            <div class="items">
                                    <div class="leftname">重发次数：</div>
                                    <el-input v-model="MorddeviceInfo.resend_count" placeholder="[1-10数字]"></el-input>
                            </div>
                            <div class="items">
                                    <div class="leftname">中断次数：</div>
                                    <el-input v-model="MorddeviceInfo.break_count" placeholder="[1-10数字]"></el-input>
                            </div>
                            
                            <div class="items">
                                <div class="leftname">设备投运：</div>
                                <el-checkbox v-model="MorddeviceInfo.run"></el-checkbox>
                            </div>

                            
                    </div>
                    <div class="el-loading-mask" v-show="diaisMask">
                                    <div class="el-loading-spinner">
                                    <svg viewBox="25 25 50 50" class="circular">
                                        <circle cx="50" cy="50" r="20" fill="none" class="path"></circle>
                                    </svg>
                           </div>
                     </div>
                   <template #footer >
                      <div class="dialog-footer">
                            <el-button  @click="addMord = false" >取 消</el-button>
                            <el-button  class="last-el-button"  type="primary" @click="BatchIncrease">确 定</el-button>
                      </div>
                    </template>
          </el-dialog>
          <!-- 批量修改设备 -->
          <el-dialog width="580px" draggable  title="批量修改设备" :close-on-click-modal='false' v-model="editMord">
                    <div class="leftandrightdialog leftandrightdialog2">
                        <div class="items">
                                    <div class="leftname"><el-checkbox v-model="batch.device_group"></el-checkbox>设备组：</div>
                                     <el-select v-model="deviceInfo.device_group" :disabled='!batch.device_group' placeholder="设备组" @change="getDeviceMuban(deviceInfo.device_group,'手动')">
                                                <el-option
                                                v-for="item in deviceGroupList"
                                                :key="item.id"
                                                :label="item.channelName"
                                                :value="item.id">
                                                </el-option>
                                        </el-select>
                            </div>
                            <div class="items">
                                    <div class="leftname"><span></span>设备子模板：</div>
                                    <el-select v-model="deviceInfo.device_template" :disabled='!batch.device_group' placeholder="设备子模板" @change="getDeviceTempSerialList(deviceInfo.device_template,'手动')">
                                                <el-option
                                                v-for="item in deviceTemList"
                                                :key="item.id"
                                                :label="item.channelName"
                                                :value="item.id">
                                                </el-option>
                                        </el-select>
                            </div>
                            <div class="items">
                                    <div class="leftname"><span></span>设备子系列：</div>
                                   <el-select v-model="deviceInfo.device_serial_type" :disabled='!batch.device_group' placeholder="设备子系列">
                                                <el-option
                                                v-for="item in deviceSubSeriesList"
                                                :key="item.id"
                                                :label="item.serial_name"
                                                :value="item.id">
                                                </el-option>
                                        </el-select>
                            </div>
                            <div class="items">
                                    <div class="leftname"><el-checkbox v-model="batch.device_protocol"></el-checkbox>通讯协议：</div>
                                       <el-select v-model="deviceInfo.device_protocol" :disabled='!batch.device_protocol' clearable>
                                                <el-option
                                                v-for="item in thoroughfareOptionStatute"
                                                :key="item.id"
                                                :label="item.protocol_alias == '' ? item.name : item.protocol_alias"
                                                :value="item.id">
                                                </el-option>
                                        </el-select>
                            </div>
                            <div class="items">
                                    <div class="leftname"><el-checkbox v-model="batch.resend_count"></el-checkbox>重发次数：</div>
                                    <el-input v-model="deviceInfo.resend_count" :disabled='!batch.resend_count' placeholder="[1-10数字]"></el-input>
                            </div>
                            <div class="items">
                                    <div class="leftname"><el-checkbox v-model="batch.break_count"></el-checkbox>中断次数：</div>
                                    <el-input v-model="deviceInfo.break_count" :disabled='!batch.break_count' placeholder="[1-10数字]"></el-input>
                            </div>
                            
                            <div class="items">
                                <div class="leftname"><el-checkbox v-model="batch.run"></el-checkbox>设备投运：</div>
                                <el-checkbox v-model="deviceInfo.run" :disabled='!batch.run'></el-checkbox>
                            </div>
                            <div class="items">
                               <div class="leftname" style="width: 110px;min-width: 110px;"><el-checkbox v-model="batch.mychange"></el-checkbox>重新生成变量：</div>
                               <el-checkbox v-model="mychange" :disabled='!batch.mychange'></el-checkbox>
                            </div>
                            
                    </div>
                    <div class="el-loading-mask" v-show="diaisMask">
                                    <div class="el-loading-spinner">
                                    <svg viewBox="25 25 50 50" class="circular">
                                        <circle cx="50" cy="50" r="20" fill="none" class="path"></circle>
                                    </svg>
                           </div>
                     </div>
                   <template #footer >
                      <div class="dialog-footer">
                            <el-button  @click="editMord = false" >取 消</el-button>
                            <el-button  class="last-el-button"  type="primary" @click="quedingddd">确 定</el-button>
                      </div>
                    </template>
          </el-dialog>


          <el-dialog width="400px" draggable title="批量修改系数" :close-on-click-modal='false'
                            v-model="versioningvalue">
                            <div style="height:180px">
                                 <div class="input-item"> 
                                    <div class="leftname">CT转换系数</div>
                                   <el-input v-model="versionsName" style="width:240px" />
                                </div>
                                <div class="input-item"> 
                                    <div class="leftname">PT转换系数</div>
                                   <el-input v-model="versionsName" style="width:240px" />
                                </div>
                                <div class="input-item"> 
                                    <div class="leftname">功率转换系数</div>
                                   <el-input v-model="versionsName" style="width:240px" />
                                </div>
                                <div class="input-item"> 
                                    <div class="leftname">电能转换系数</div>
                                   <el-input v-model="versionsName" style="width:240px" />
                                </div>
                              
                            </div>
                            <template #footer>
                                 <div class="dialog-footer" style="display: flex;align-items: center;justify-content: center;">
                                   <div class="mybtn">保存</div>
                                   <div class="mybtn quxiao" @click="versioningvalue = false">取消</div>
                                 </div>
                            </template>
          </el-dialog>
           <!-- 新增/修改 设备-->
           <el-dialog width="1000px" draggable  :title="nowOperatingDevice" :close-on-click-modal='false' v-model="addDecive">
                    <div class="leftandrightdialog">
                        <div class="leftdio" style="margin-right:20px">
                             <div class="items">
                                <div class="leftname"><span>*</span> 设备序号：</div>
                                <div class="elinputdisabled">{{deviceInfo.device_number}}</div>
                               
                             </div>
                              <div class="items">
                                <div class="leftname"><span>*</span> 设备名称：</div>
                               <el-input v-model="deviceInfo.device_name" placeholder="请输入设备名称"></el-input>
                             </div>
                              <div class="items">
                                    <div class="leftname"><span>*</span> 设备地址：</div>
                                    <el-input v-model="deviceInfo.device_address" placeholder="请输入设备地址"></el-input>
                                </div>
                              <div class="items">
                                    <div class="leftname">扩展地址：</div>
                                      <el-input v-model="deviceInfo.device_addressex" placeholder="请输入扩展地址"></el-input>
                                </div>
                                <div class="items">
                                <div class="leftname">通讯协议：</div>
                                <el-select v-model="deviceInfo.device_protocol" clearable>
                                                <el-option
                                                v-for="item in thoroughfareOptionStatute"
                                                :key="item.id"
                                                :label="item.protocol_alias == '' ? item.name : item.protocol_alias"
                                                :value="item.id">
                                                </el-option>
                                        </el-select>
                                </div>
                                <div class="items">
                                <div class="leftname">设备投运：</div>
                                <el-checkbox v-model="deviceInfo.run"></el-checkbox>
                            </div>
                             <div class="items">
                               <div class="leftname"> 重新生成变量：</div>
                               <el-checkbox v-model="mychange"></el-checkbox>
                            </div>


                        </div>
                        <div class="leftdio">
                            <div class="items">
                                    <div class="leftname">设备组：</div>
                                     <el-select v-model="deviceInfo.device_group" placeholder="设备组" @change="getDeviceMuban(deviceInfo.device_group,'手动')">
                                                <el-option
                                                v-for="item in deviceGroupList"
                                                :key="item.id"
                                                :label="item.channelName"
                                                :value="item.id">
                                                </el-option>
                                        </el-select>
                            </div>
                            <div class="items">
                                    <div class="leftname">设备子模板：</div>
                                    <el-select v-model="deviceInfo.device_template" placeholder="设备子模板" @change="getDeviceTempSerialList(deviceInfo.device_template,'手动')">
                                                <el-option
                                                v-for="item in deviceTemList"
                                                :key="item.id"
                                                :label="item.channelName"
                                                :value="item.id">
                                                </el-option>
                                        </el-select>
                            </div>
                            <div class="items">
                                    <div class="leftname">设备子系列：</div>
                                   <el-select v-model="deviceInfo.device_serial_type" placeholder="设备子系列">
                                                <el-option
                                                v-for="item in deviceSubSeriesList"
                                                :key="item.id"
                                                :label="item.serial_name"
                                                :value="item.id">
                                                </el-option>
                                        </el-select>
                            </div>
                            <div class="items itemright">
                                <div class="leftname"><span>*</span> 中断次数：</div>
                               <el-input v-model="deviceInfo.break_count" placeholder="[1-10数字]"></el-input>
                            </div>
                             <div class="items itemright">
                                <div class="leftname"><span>*</span> 重发次数：</div>
                               <el-input v-model="deviceInfo.resend_count" placeholder="[1-10数字]"></el-input>
                            </div>
                        </div>
                    </div>
                    <div class="el-loading-mask" v-show="diaisMask">
                                    <div class="el-loading-spinner">
                                    <svg viewBox="25 25 50 50" class="circular">
                                        <circle cx="50" cy="50" r="20" fill="none" class="path"></circle>
                                    </svg>
                           </div>
                     </div>
                   <template #footer >
                      <div class="dialog-footer">
                            <el-button  @click="addDecive = false" >取 消</el-button>
                            <el-button  class="last-el-button" @click="saveDevicefn" type="primary">确 定</el-button>
                      </div>
                    </template>
           </el-dialog>

           <!-- 导入EXCEL名称重复提醒 -->
          <el-dialog width="1100px" draggable  title="导入模版(EXCEL)提示"   v-model="daorudiofalseEXCEL" :close-on-click-modal='false'>
                    <div class="choicedio">
                         <div style="color:red;font-size:16px">提示：存在重复名称的数据，只取第一条</div>
                         <div class="mytitle" style="margin-top:8px;margin-bottom:12px">
                                <span></span>设备重复名称的数据列表
                         </div>
                         <div class="diatable" style="width:100%;height:400px">
                            <el-table :data="repeatDataArea" height="100%" stripe  style="width: 100%;">
                                    <el-table-column type="index"  width="50" label="序号" align="center"> </el-table-column>
                                    <el-table-column prop="设备名称"  label="设备名称"> </el-table-column>
                                    <el-table-column prop="设备地址"  label="设备地址"> </el-table-column>
                                    <el-table-column  prop="扩展地址" label="扩展地址"></el-table-column>

                            </el-table>
                             
                         </div>
                    </div>
                      <template #footer>
                            <div class="dialog-footer">
                                 <el-button  @click="daorudiofalseEXCEL = false" type="warning">取消上传</el-button>
                                 <el-button  class="last-el-button"  type="primary" @click="chulihanshu">确 定</el-button>
                            </div>
                    </template> 
         </el-dialog>
           
          <div class="el-loading-mask" v-show="isMask">
             <div class="el-loading-spinner"><svg viewBox="25 25 50 50" class="circular"> <circle cx="50" cy="50" r="20" fill="none" class="path"></circle></svg></div>
          </div>

        </div>
    </div>
</template>

<script>
import {findchannelconfigAll,findDeviceGroupListAll,findDeviceGroupList,findDeviceTemplate,findDeviceSerial} from "../api/dataComparisonApi";
import {infoPtlSo,getDeviceList,addDevicechun,batchAddDevicechun,editDevicechun,batchEditDevicechun,delDevicechun,batchDelDevicechun,getVariablesDevice,commondatatype} from "../api/Interface";
import {getDeviceconfigidleNumber} from "../api/forwardApi";
import { useCounterStore } from '../stores/counter'
import { saveAs } from 'file-saver';
import * as XLSX from "xlsx"; 
export default {
    data() {
        return {
            addMord:false,//批量新增设备
            progress:0,
            MorddeviceInfo:{
                prefix:"",
                startNumber:"",
                suffix:"",
                number:"",
                device_address:0,
                device_addressex:"",
                device_group:"",
                device_template:"",
                device_serial_type:"",
                device_protocol:"",
                resend_count:3,
                break_count:1,
                run:true,
            },
            treeflag: true,//显示树形
            diaisMask:false,
            // optionsType:[],//数据类型
            isMask:false,
            total:0,
            currentPage:1,
            data_bitsList:[],
            leftTable:[],//设备表格
            leftTable111:[],//设备表格
            leftTableCopy:[],
            versionsName:"",
            search:{
                device_name:"",
                device_group:"",
                device_template:"",
                device_serial_type:"",
                device_protocol:"",
                device_address:"",
                device_addressex:"",
            },//搜索
            runList:[
                {
                    'label':"投运",
                    'value':1,
                },
                {
                    'label':"退出",
                    'value':2,
                },
            ],
            nowLeftRow:{},
            thoroughfareOptionStatute:[],//规约
            leftData:[],
            nowOperatingDevice:"添加设备",
            adddrawer:false,//新增变量
            drawTable:[],
            deviceInfo:{
                device_name:"",
                device_addressex:"",
                device_address:"",
                device_number:"",
                device_protocol:"",
                device_group:"",
                device_template:"",
                device_serial_type:"",
                break_count:"",
                resend_count:"",
                run:true,
            },//设备信息
            mychange:false,
             regionList:[
            {
                'name':"默认区域",
                'id':0
            }
              ],//所属区域
            deviceGroupList:[],//设备组
            deviceArr:[],
            deviceTemList:[
                {
                             'channelName':"无",
                             'id':'0',
                             'device_group_id':0,
                             'type':"设备模板",
                }
            ],//设备组模板
            deviceSubSeriesList:[
                {
                             'serial_name':"无",
                             'id':'0',
                             'device_group_id':0,
                             'type':"设备子系列",
                }
            ],//设备子系列
            addDecive:false,//新增设备
            checked:false,
            editMord:false,//批量修改
            versioningvalue:false,//批量修改系数
            gudingchannel_number:"",//空闲的设备号

            deviceGroundAll:[],//设备组
            deviceMunbanAll:[],//设备模板
            deviceSonAll:[],//设备子系列
            editNum:1,
            multipleSelection:[],
            //批量修改选择
            batch:{
               device_group:false,
               device_protocol:false,
               resend_count:false,
               break_count:false,
               run:false,
               mychange:false
            },
            repeatDataArea:[],
            daorudiofalseEXCEL:false,

        };
    },

    mounted() {
        this.getALLDeviceMuban()
        this.getinfoPtlSo()
        // this.getfindchannelconfigAll()
        this.getDeviceGroupApi()
        this.getDeviceconfigidleNumberfn()
        
    },
    computed: {
       optionsType(){
          return useCounterStore().mydataType
       },
    },

    methods: {
        //查看全部设备
        viewAllDecice(){
            this.nowLeftRow = {}
            this.leftTableCopy = JSON.parse(JSON.stringify(this.deviceArr))
            this.leftTable = this.getCurrentPageData(this.leftTableCopy,this.currentPage,50)
            this.total = this.deviceArr.length
        },
        //查询空闲的设备号
        getDeviceconfigidleNumberfn(){
            getDeviceconfigidleNumber().then(res => { 
                if(res != undefined){
                this.gudingchannel_number = res.idle
                }
            })
        },
        //搜索
        searchFN(){
             var filterArr = this.leftTableCopy.filter(item => item.device_name.includes(this.search.device_name))
           
             filterArr = filterArr.filter(item => String(item.device_group).includes(this.search.device_group))
             filterArr = filterArr.filter(item => String(item.device_template).includes(this.search.device_template))
             filterArr = filterArr.filter(item => String(item.device_serial_type).includes(this.search.device_serial_type))
             filterArr = filterArr.filter(item => String(item.device_protocol).includes(this.search.device_protocol))
             filterArr = filterArr.filter(item => String(item.device_address).includes(this.search.device_address))
             filterArr = filterArr.filter(item => String(item.device_addressex).includes(this.search.device_addressex))

             if(this.search.device_address != ""){
                 filterArr = filterArr.filter(item => item.device_address == this.search.device_address)
             }
             if(this.search.device_addressex != ""){
                 filterArr = filterArr.filter(item => item.device_addressex == this.search.device_addressex)
             }
             
             this.leftTable = filterArr
             this.total = this.leftTable.length
        },
        //重置搜索
        chongzhifn(){
            this.search = {
                device_name:"",
                device_group:"",
                device_template:"",
                device_serial_type:"",
                device_protocol:"",
                device_address:"",
                device_addressex:"",
            }

            this.leftTable = this.leftTableCopy

        },
        //获取数据类型
        getcommondatatype(){
            commondatatype().then(res => {
                  this.optionsType = res
            })
        },
        handleSizeChangejiao(val){
            this.currentPage=val;
            this.leftTable = this.getCurrentPageData(this.leftTableCopy,this.currentPage,50)
        },
        handleCurrentChangejiao(val){
            this.currentPage=val;
            this.leftTable = this.getCurrentPageData(this.leftTableCopy,this.currentPage,50)
        },
        getCurrentPageData(dataList, page, size) {
            // 计算并返回当前页数据
            var res = dataList.slice((page-1)*size, page*size)
            return res
        },
         //查询规约
        getinfoPtlSo(){
            infoPtlSo().then(res => {
                var wuArr =[{
                      "hide": 1,
                      "id": 0,
                      "name": "无",
                      "protocol_name": "无",
                      "status": 1,
                      "protocol_alias":"",
                      "suffix": ".so"
                  }]
                  if(res != undefined){
                      this.thoroughfareOptionStatute = wuArr.concat(res)
                  }
            })
        },
         //获取设备组
        getDeviceGroupApi(){
            this.diaisMask = true
            this.deviceGroupList = [
                {
                    'channelName':'无',
                    'id':'0',
                    'type':"模板组",
                }
            ]
             findDeviceGroupList().then(res => {
                if(res){
                    res.forEach(item => {
                          this.deviceGroupList.push({
                             'channelName':item.device_group_name,
                             'id':item.id,
                             'type':"模板组",
                          })
                    })
                }
                this.diaisMask = false
            }).catch(() => {
                     this.diaisMask = false
              })
        },
        //获取全部设备模板、子系列
        getALLDeviceMuban(){
            findDeviceGroupListAll().then(res => {
                this.diaisMask = false
                if(res != undefined){
                     var RESDATA = res
                     var arr1 = [
                        {
                            'device_group_name':'无',
                            'id':'0',
                            'type':"模板组",
                        }
                     ]
                     var arr2 = [
                        {
                             'device_template_name':"无",
                             'id':'0',
                             'device_group_id':0,
                             'type':"设备模板",
                }
                     ]
                     var arr3 = [
                        {
                             'serial_name':"无",
                             'id':'0',
                             'device_group_id':0,
                             'type':"设备子系列",
                }
                     ]
                     RESDATA.forEach(item => {
                         //第一层为模板组
                         arr1.push(item)
                         //第二层为设备模板
                         item.children.forEach(towitem => {
                            arr2.push(towitem)
                            //第三层为设备子系列
                            towitem.children.forEach(threeitem => {
                                 arr3.push(threeitem)
                            })
                         })
                     })
                     this.deviceGroundAll = arr1
                     this.deviceMunbanAll = arr2
                     this.deviceSonAll = arr3
                     this.getfindchannelconfigAll()
                }
            }).catch(() => {
                this.diaisMask = false
            })
        },
        //获取设备模板
        getDeviceMuban(row,type){
            if(row === "" || row === "0"){
                this.deviceTemList = [{
                             'channelName':"无",
                             'id':"0",
                             'device_group_id':0,
                             'type':"设备模板",
                }]
                this.deviceInfo.device_template = "0"
                this.deviceSubSeriesList = [
                    {
                      'serial_name':"无",
                      'id':'0',
                      'device_group_id':0,
                      'type':"设备子系列",
                    }
                ]
                this.deviceInfo.device_serial_type = "0"
               return
            }
            if(row == undefined){
               this.deviceInfo.device_template = ""
               this.deviceInfo.device_serial_type = ""
               return
            }
            this.diaisMask = true
            // this.isMask = true
             findDeviceTemplate(row).then(res => {
                   if(res){
                    var arr = []
                    res.forEach(item => {
                          arr.push({
                             'channelName':item.device_template_name,
                             'id':item.id,
                             'device_group_id':item.device_group_id,
                             'type':"设备模板",
                          })
                    })
                    this.deviceTemList = arr
                    if(type == '手动' && this.deviceTemList.length != 0){
                          this.deviceInfo.device_template = this.deviceTemList[0].id
                          this.getDeviceTempSerialList(this.deviceTemList[0].id,'手动')
                    }
                }
                   this.diaisMask = false
                    // this.isMask = false
             }).catch(() => {
                     this.diaisMask = false
                    //   this.isMask = false
              })
        },
        //查询设备模板的子系列
        getDeviceTempSerialList(row,type){
            // var d = {
            //       "device_template_id":row
            // }
            if(row === "" || row === 0){
                return
            }
            this.diaisMask = true
            // this.isMask = true
            findDeviceSerial(row).then(res => {
                  this.diaisMask = false
                   this.isMask = false
                 if(res){
                   
                     this.deviceSubSeriesList = res
                     if(type =='手动' && res.length != 0){
                          this.deviceInfo.device_serial_type = res[0].id
                     }
                 }
            }).catch(() => {
                     this.diaisMask = false
                    //   this.isMask = false
              })
        },
         //获取表格列表
        getfindchannelconfigAll(){
         this.isMask = true
         var arr1 = [
            {
                channel_name:"全部设备",
            }
         ]
            findchannelconfigAll().then(res => {
            this.isMask = false
            if(res == ""){
                this.leftData = []
            }else {
                this.leftData = arr1.concat(res)
                if(this.nowLeftRow.channel_id){
                    this.getDeviceListData()
                }else {
                    if(res.length != 0){
                        this.nowLeftRow = res[0]
                        this.getDeviceListData()
                    }
                }
                
            }
            
            })
        },
        //获取所有设备
        getDeviceListData(){
              getDeviceList().then(res => {
                   this.deviceArr = res
                   var arr1 = []
                   var arr2 = []
                   var arr3 = []
                   var arr4 = []
                   this.deviceArr.forEach(item => {
                    item.run = item.run == 1 ? true : false
                    arr1 =  this.thoroughfareOptionStatute.filter(tt => tt.id == item.device_protocol)
                    if(arr1.length != 0){
                        item.device_protocol_name = arr1[0].name
                    }else {
                        item.device_protocol_name = ""
                    }
                    //设备组
                    arr2 =  this.deviceGroundAll.filter(tt => tt.id == item.device_group)
                    item.device_group_name = arr2.length != 0 ? arr2[0].device_group_name : ""
                    //设备模板
                    arr3 =  this.deviceMunbanAll.filter(tt => tt.id == item.device_template)
                    item.device_template_name = arr3.length != 0 ? arr3[0].device_template_name : ""
                    //设备子系列
                    arr4 =  this.deviceSonAll.filter(tt => tt.id == item.device_serial_type)
                    item.device_serial_type_name = arr4.length != 0 ? arr4[0].serial_name : ""
                    })
                   this.leftRowfn()
              })
        },
        //处理设备
        leftRowfn(){
            var ResData = []
            if(this.nowLeftRow.channel_name == '全部设备'){
                ResData = this.deviceArr
            }else {
                ResData = this.deviceArr.filter(item => item.channel_number == this.nowLeftRow.channel_number)
            }
            this.currentPage = 1
            this.leftTableCopy = JSON.parse(JSON.stringify(ResData))
            this.leftTable = this.getCurrentPageData(this.leftTableCopy,this.currentPage,50)
            this.total = ResData.length
        },
        //批量新增设备
        mordaddDecivefn(){
            if(this.leftData.length == 0 || this.nowLeftRow.channel_name == '全部设备'){
                this.$message({showClose: true,message: '请选择通道',type: 'warning'});
                return
            }
            this.MorddeviceInfo = {
                prefix:"",
                startNumber:"",
                suffix:"",
                number:"",
                device_address:0,
                device_addressex:"",
                device_group:"0",
                device_template:"0",
                device_serial_type:"0",
                device_protocol:0,
                resend_count:3,
                break_count:1,
                run:true,
            }
            this.deviceInfo.device_group = "0"
            this.deviceInfo.device_template = "0"
            this.deviceInfo.device_serial_type = "0"
            this.deviceTemList = [
                {
                             'channelName':"无",
                             'id':'0',
                             'device_group_id':0,
                             'type':"设备模板",
                }
            ]
            this.deviceSubSeriesList = [
                {
                             'serial_name':"无",
                             'id':'0',
                             'device_group_id':0,
                             'type':"设备子系列",
                }
            ]
            this.addMord = true
        },
        //确定批量增加设备
        BatchIncrease(){
            if(this.MorddeviceInfo.prefix === ""){
                this.$message({showClose: true,message: '设备名称前缀不能为空',type: 'warning'});
                return
            }
            if(this.MorddeviceInfo.startNumber === ""){
                this.$message({showClose: true,message: '设备名称起始编号不能为空',type: 'warning'});
                return
            }
            if(this.MorddeviceInfo.device_address === ""){
                this.$message({showClose: true,message: '设备起始地址不能为空',type: 'warning'});
                return
            }
            if(this.MorddeviceInfo.number === ""){
                this.$message({showClose: true,message: '设备个数不能为空',type: 'warning'});
                return
            }
            if(Number(this.MorddeviceInfo.number) === 0){
                this.$message({showClose: true,message: '设备个数不能为0',type: 'warning'});
                return
            }
            //判断正整数
            function isPositiveInteger(str) {
             return /^(0|[1-9]\d*)$/.test(str);
            }
            if(!isPositiveInteger(this.MorddeviceInfo.startNumber)){
                this.$message({showClose: true,message: '设备起始编号格式不正确，必须为正整数',type: 'warning'});
                return
            }
            if(!isPositiveInteger(this.MorddeviceInfo.number)){
                this.$message({showClose: true,message: '设备个数格式不正确，必须为正整数',type: 'warning'});
                return
            }
            if(!isPositiveInteger(this.MorddeviceInfo.device_address)){
                this.$message({showClose: true,message: '设备起始地址格式不正确，必须为正整数',type: 'warning'});
                return
            }
            var dd = []
            for (let i = 0; i < Number(this.MorddeviceInfo.number); i++) {
             dd.push({
                        "channel_number": Number(this.nowLeftRow.channel_number),
                        "device_number": this.gudingchannel_number + i,
                        "device_name": this.MorddeviceInfo.prefix+(Number(this.MorddeviceInfo.startNumber)+i)+this.MorddeviceInfo.suffix,
                        "device_address": Number(this.MorddeviceInfo.device_address) + i,
                        "device_addressex": this.MorddeviceInfo.device_addressex,
                        "device_group": this.deviceInfo.device_group === "" ? 0 : Number(this.deviceInfo.device_group),
                        "device_template": this.deviceInfo.device_template === "" ? 0 : Number(this.deviceInfo.device_template),
                        "device_serial_type": this.deviceInfo.device_serial_type === "" ? 0 : Number(this.deviceInfo.device_serial_type),
                        "device_protocol":this.MorddeviceInfo.device_protocol === "" ? 0 : Number(this.MorddeviceInfo.device_protocol),
                        "resend_count": Number(this.MorddeviceInfo.resend_count),
                        "break_count": Number(this.MorddeviceInfo.break_count),
                        "run": this.MorddeviceInfo.run ? 1 : 0,
                        "change": 0,
                })
            }
            // 创建 arr2 的 device_name 集合
            const arr2Names = new Set(this.deviceArr.map(item => item.device_name));
            // 筛选 arr1 中存在于 arr2Names 的元素
            var commonElements = dd.filter(item => arr2Names.has(item.device_name));
            if(commonElements.length != 0){
                var arrname = []
                commonElements.forEach(item => arrname.push(item.device_name))
                this.$message({showClose: true,message: arrname.join()+' 设备名称已存在！！',type: 'warning'});
                return
            }
            this.diaisMask = true
            batchAddDevicechun(dd).then(res => {
                this.diaisMask = false
                 if(res.code == 200){
                    this.addMord = false
                    this.getDeviceconfigidleNumberfn()
                    this.$message({showClose: true,message: '批量新增成功',type: 'success'});
                    this.getfindchannelconfigAll()
                 }else {
                     this.$message({showClose: true,message: '保存失败',type: 'error'});
                 }
            })
            //旧批量新增设备(前端弄)
            // this.startSequentialRequests(dd)

        },
        // 执行一组 POST 请求
        async executeRequestsSequentially(requests) {
        const results = [];
        
        for (const request of requests) {
            try {
            // 等待当前请求完成
            const response = await addDevicechun(request);
            // results.push(response);
            
            // 可选：更新 UI 或显示进度
            // this.progress = (results.length / requests.length) * 100;
            } catch (error) {
            // console.error('请求失败:', request, error);
            // 根据需求决定是否继续或中断
            // break; // 如果需要失败时停止，取消注释
            // results.push({ error: true, message: error.message });
            }
        }
        
        return results;
        },
        
        // 示例调用方法
        async startSequentialRequests(requestList) {
            // this.isMask = true;
            const results = await this.executeRequestsSequentially(requestList);
            // this.isMask = false;
            this.addMord = false
            this.getDeviceconfigidleNumberfn()
            this.$message({showClose: true,message: '批量新增成功',type: 'success'});
            this.getfindchannelconfigAll()
            // 处理最终结果
        },
        //新增设备
        addDecivefn(){

            // this.nowLeftRow
            // channel_protocol
            if(this.leftData.length == 0 || this.nowLeftRow.channel_name == '全部设备'){
                this.$message({showClose: true,message: '请选择通道',type: 'warning'});
                return
            }
             this.mychange = false
             this.nowOperatingDevice = "添加设备"
             this.deviceInfo = {
                protocolType:0,
                device_name:"",
                device_addressex:"",
                device_address:"0",
                device_number:this.gudingchannel_number,
                device_protocol:this.thoroughfareOptionStatute.length != 0 ? this.thoroughfareOptionStatute[0].id : "",
                device_group:"0",
                device_template:"0",
                device_serial_type:"0",
                break_count:"1",
                resend_count:"3",
                run:true,
                change:false,
                mqtt:false
             }
             this.deviceTemList = [
                {
                             'channelName':"无",
                             'id':'0',
                             'device_group_id':0,
                             'type':"设备模板",
                }
            ]
            this.deviceSubSeriesList = [
                {
                             'serial_name':"无",
                             'id':'0',
                             'device_group_id':0,
                             'type':"设备子系列",
                }
            ]
             if(this.nowLeftRow.channel_protocol != ""){
                 this.deviceInfo.device_protocol = this.nowLeftRow.channel_protocol
             }
             this.addDecive = true
        },
        //修改设备
        editDevice(row){
            this.editNum = 1
            this.nowOperatingDevice = `修改设备(${row.device_name})`
            this.deviceInfo = row
            this.deviceInfo.protocolType = 0
            this.deviceInfo.device_group =  this.deviceInfo.device_group === 0 ? String(this.deviceInfo.device_group) :this.deviceInfo.device_group
            this.deviceInfo.device_template =  this.deviceInfo.device_template === 0 ? String(this.deviceInfo.device_template) :this.deviceInfo.device_template
            this.deviceInfo.device_serial_type =  this.deviceInfo.device_serial_type === 0 ? String(this.deviceInfo.device_serial_type) :this.deviceInfo.device_serial_type
            this.getDeviceMuban(row.device_group,'自动')
            this.getDeviceTempSerialList(row.device_template,'自动')
            this.addDecive = true
        },
        //保存设备信息
        saveDevicefn(){
            
            if(this.deviceInfo.device_name === ""){
                this.$message({showClose: true,message: '设备名称不能为空',type: 'warning'});
                return
            }
            if(this.deviceInfo.device_address === ""){
                this.$message({showClose: true,message: '设备地址不能为空',type: 'warning'});
                return
            }
            if(this.deviceInfo.break_count === ""){
                this.$message({showClose: true,message: '中断次数不能为空',type: 'warning'});
                return
            }
            if(this.deviceInfo.resend_count === ""){
                this.$message({showClose: true,message: '重发次数不能为空',type: 'warning'});
                return
            }
           
            if(!Number.isInteger(Number(this.deviceInfo.break_count))){
                this.$message({showClose: true,message: '中断次数为[1-10整数]',type: 'warning'});
                return
            }
            if(!Number.isInteger(Number(this.deviceInfo.resend_count))){
                this.$message({showClose: true,message: '重发次数为[1-10整数]',type: 'warning'});
                return
            }
            if(Number(this.deviceInfo.break_count) < 1 || Number(this.deviceInfo.break_count) > 10){
                this.$message({showClose: true,message: '中断次数为[1-10整数]',type: 'warning'});
                return
            }
            if(Number(this.deviceInfo.resend_count) < 1 || Number(this.deviceInfo.resend_count) > 10){
                this.$message({showClose: true,message: '重发次数为[1-10整数]',type: 'warning'});
                return
            }
             var d = {
                        "channel_number": Number(this.nowLeftRow.channel_number),
                        "device_number": Number(this.deviceInfo.device_number),
                        "device_name": this.deviceInfo.device_name,
                        "device_address": Number(this.deviceInfo.device_address),
                        // "device_addressex": Number(this.deviceInfo.device_addressex),
                        "device_addressex": this.deviceInfo.device_addressex,
                        "device_group": (this.deviceInfo.device_group === "" || this.deviceInfo.device_group === undefined) ? 0 : Number(this.deviceInfo.device_group),
                        "device_template": (this.deviceInfo.device_template === "" || this.deviceInfo.device_template === undefined) ? 0 : Number(this.deviceInfo.device_template),
                        "device_serial_type": (this.deviceInfo.device_serial_type === "" || this.deviceInfo.device_serial_type === undefined) ? 0 : Number(this.deviceInfo.device_serial_type),
                        "device_protocol":this.deviceInfo.device_protocol,
                        "resend_count": Number(this.deviceInfo.resend_count),
                        "break_count": Number(this.deviceInfo.break_count),
                        "run": this.deviceInfo.run ? 1 : 0,
                        "change": this.mychange ? 1 : 0,
                }
                if(this.nowOperatingDevice == '添加设备'){
                    var ResData  = this.deviceArr.filter(item => item.device_name == this.deviceInfo.device_name)
                    if(ResData.length != 0){
                        this.$message({showClose: true,message: '设备名称已重复，请重新更换！',type: 'warning'});
                        return
                    }
                     this.isMask = true
                     addDevicechun(d).then(res => {
                        this.isMask = false
                          if(res.code == 200){
                                this.addDecive = false
                                this.getDeviceconfigidleNumberfn()
                                this.$message({showClose: true,message: '保存成功',type: 'success'});
                                this.getfindchannelconfigAll()
                            }else {
                                this.$message({showClose: true,message: '保存失败',type: 'error'});
                            }
                     }).catch(() => {
                         this.isMask = false
                     })
                }else {
                    d.device_id = this.deviceInfo.device_id
                    d.channel_number = this.deviceInfo.channel_number
                    //   d.change = 1
                       this.isMask = true
                     editDevicechun(d).then(res => {
                           this.isMask = false
                          if(res.code == 200){
                            this.addDecive = false
                            this.$message({showClose: true,message: '保存成功',type: 'success'});
                            this.getfindchannelconfigAll()
                            }else {
                                this.$message({showClose: true,message: '保存失败',type: 'error'});
                            }
                     }).catch(() => {
                         this.isMask = false
                     })
                }
        },
        //删除设备
        delDioFN(row){
            this.$confirm(`是否要删除此项？`,'提示',{
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
               delDevicechun(row.device_id).then(res => {
                  if(res.code == 200){
                     this.getDeviceconfigidleNumberfn()
                     this.$message({showClose: true,message: '删除成功',type: 'success'});
                    this.getDeviceListData()
                  }else {
                      this.$message.error('删除失败！！')
                  }
               }).catch(error => {
                    this.$message.error('删除失败！！')
               })
              
        
                      
            }).catch(() => {
              // ...
            });
        },
        //变量抽屉
        VariableDrawfn(row){
              getVariablesDevice(row.device_id).then(res => {
                       this.adddrawer = true
                      if(res != undefined){
                        this.drawTable = res
                       
                      }
                 })
        },
        //选择设备
        handleSelectionChange(val){
            this.multipleSelection = val
        },
        //批量修改设备
        editMordfn(){
            
            if(this.multipleSelection.length === 0){
                this.$message({showClose: true,message: '请选择需要修改的设备',type: 'warning'});
                return
            }
            this.deviceInfo = {
                device_name:"",
                device_addressex:"",
                device_address:"",
                device_number:"",
                device_protocol:"",
                device_group:"",
                device_template:"",
                device_serial_type:"",
                break_count:"",
                resend_count:"",
                run:false,
            }
            this.mychange = false
            this.batch = {
               device_group:false, //设备组
               device_protocol:false, //设备规约
               resend_count:false, // 重发次数
               break_count:false, //中断次数
               run:false, //是否投运
               mychange:false,
            }
             this.editMord = true
        },
        //确定批量修改
        quedingddd(){
            
            var arr1 = []
            this.multipleSelection.forEach(item => {
                 arr1.push({
                    "break_count": item.break_count,
                    "channel_number": item.channel_number,
                    "device_address": item.device_address,
                    "device_addressex": item.device_addressex,
                    "device_group": item.device_group,
                    "device_id": item.device_id,
                    "device_name": item.device_name,
                    "device_number": item.device_number,
                    "device_protocol": item.device_protocol,
                    "device_serial_type": item.device_serial_type,
                    "device_template": item.device_template,
                    "resend_count": item.resend_count,
                    "run": item.run,
                    'change':0
                })
            })
            
            //批量修改选择
            // batch:{
            //    device_group:false, //设备组
            //    device_protocol:false, //设备规约
            //    resend_count:false, // 重发次数
            //    break_count:false, //中断次数
            //    run:false, //是否投运
            // }
            if(this.batch.break_count){
                if(this.deviceInfo.break_count === ""){
                    this.$message({showClose: true,message: '中断次数不能为空',type: 'warning'});
                    return
                }
                if(Number(this.deviceInfo.break_count) < 1 || Number(this.deviceInfo.break_count) > 10){
                    this.$message({showClose: true,message: '中断次数为[1-10整数]',type: 'warning'});
                    return
                }
                if(!Number.isInteger(Number(this.deviceInfo.break_count))){
                    this.$message({showClose: true,message: '中断次数为[1-10整数]',type: 'warning'});
                    return
                }
            }
            if(this.batch.resend_count){
                if(this.deviceInfo.resend_count === ""){
                    this.$message({showClose: true,message: '重发次数不能为空',type: 'warning'});
                    return
                }
                if(!Number.isInteger(Number(this.deviceInfo.resend_count))){
                    this.$message({showClose: true,message: '重发次数为[1-10整数]',type: 'warning'});
                    return
                }
                if(Number(this.deviceInfo.resend_count) < 1 || Number(this.deviceInfo.resend_count) > 10){
                    this.$message({showClose: true,message: '重发次数为[1-10整数]',type: 'warning'});
                    return
                }
            }


            arr1.forEach(item => {
                item.run =  item.run ? 1 : 0
                if(this.batch.device_group){
                    item.device_group = this.deviceInfo.device_group === "" ? 0 : this.deviceInfo.device_group
                    item.device_template = this.deviceInfo.device_template === "" ? 0 : this.deviceInfo.device_template
                    item.device_serial_type = this.deviceInfo.device_serial_type === "" ? 0 : this.deviceInfo.device_serial_type
                }
                if(this.batch.device_protocol){
                    item.device_protocol = this.deviceInfo.device_protocol === "" ? 0 : this.deviceInfo.device_protocol
                }
                if(this.batch.resend_count){
                    item.resend_count = Number(this.deviceInfo.resend_count)
                }
                if(this.batch.break_count){
                    item.break_count = Number(this.deviceInfo.break_count)
                }
                if(this.batch.run){
                    item.run =  this.deviceInfo.run ? 1 : 0
                }
                if(this.batch.mychange){
                    item.change =  this.mychange ? 1 : 0
                }
            })
            this.isMask = true
            batchEditDevicechun(arr1).then(res => {
                this.isMask = false
                if(res.code == 200){
                    this.editMord = false
                    this.getDeviceconfigidleNumberfn()
                    this.$message({showClose: true,message: '保存成功',type: 'success'});
                    this.getfindchannelconfigAll()
                }else {
                    this.$message({showClose: true,message: '保存失败',type: 'error'});
                }
            })
             
        },
        //批量删除
        delMordfn(){
            if(this.multipleSelection.length === 0){
                this.$message({showClose: true,message: '请选择需要删除的设备',type: 'warning'});
                return
            }
            this.$confirm(`确定要删除选中的设备吗？`,'提示',{
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
                var arr1 = []
                this.multipleSelection.forEach(item => arr1.push(item.device_id))
                 this.isMask = true
               batchDelDevicechun(arr1).then(res => {
                this.isMask = false
                  if(res.code == 200){
                     this.getDeviceconfigidleNumberfn()
                     this.$message({showClose: true,message: '删除成功',type: 'success'});
                    this.getDeviceListData()
                  }else {
                      this.$message.error('删除失败！！')
                  }
               }).catch(error => {
                    this.$message.error('删除失败！！')
               })
              
        
                      
            }).catch(() => {
              // ...
            });

        },
        //导出设备信息
        ExportTemplateEXCEL(){

            var tableData11 = []
            this.leftTableCopy.forEach(item => {
                 tableData11.push({
                    // '设备号':String(item.device_number),
                    '设备名称':item.device_name,
                    '设备地址':String(item.device_address),
                    '扩展地址':String(item.device_addressex),
                    // '设备组':(item.device_group),
                    // '设备模版':item.device_template,
                    // '系列类型':item.device_serial_type,
                    '设备组':0,
                    '设备模版':0,
                    '系列类型':0,
                    '通讯协议':String(item.device_protocol),
                    '中断次数':item.break_count,
                    '重发次数':item.resend_count,
                    '是否投运':item.run ? '是' : '否',
                    'MQTT设备':item.mqtt == 1 ? '是' : '否',
                 })
            })

            var tableData33 =  []
            this.thoroughfareOptionStatute.forEach(item => {
                tableData33.push({
                    '编码':item.id,
                    '名称':item.name,
                    '别名':item.protocol_alias,
                })
            })

            var tableData44 =  []
            this.deviceGroundAll.forEach(item => {
                tableData44.push({
                    '编码':item.id,
                    '名称':item.device_group_name,
                })
            })

            var tableData55 =  []
            this.deviceMunbanAll.forEach(item => {
                tableData55.push({
                    '编码':item.id,
                    '名称':item.device_template_name,
                })
            })

            var tableData66 =  []
            // 添加数据编码区块
            this.deviceSonAll.forEach(item => {
                tableData66.push({
                    '编码':item.id,
                    '名称':item.serial_name,
                })
            })

            // 1. 创建工作簿
            const workbook = XLSX.utils.book_new();

            // 2. 将数组对象转换为工作表
            const worksheet = XLSX.utils.json_to_sheet(tableData11);
            const worksheet6 = XLSX.utils.json_to_sheet(tableData33);
            const worksheet7 = XLSX.utils.json_to_sheet(tableData44);
            const worksheet8 = XLSX.utils.json_to_sheet(tableData55);
            const worksheet9 = XLSX.utils.json_to_sheet(tableData66);

         
            
            

             // 自定义列宽
            worksheet['!cols'] = [
                { wch: 10 },  
                { wch: 25 }, 
                { wch: 12 },  
                { wch: 12 },  
                { wch: 25 },  
                { wch: 25 },  
                { wch: 25 },  
                { wch: 25 },  
            ];
             // 5. 设置列宽
            worksheet6['!cols'] = [
                { wch: 10 },  // 第一列宽度
                { wch: 40 },   // 第二列宽度
                { wch: 40 }   // 第二列宽度
            ]
             // 5. 设置列宽
            worksheet7['!cols'] = [
                { wch: 10 },  // 第一列宽度
                { wch: 40 },   // 第二列宽度
                { wch: 40 }   // 第二列宽度
            ]
             // 5. 设置列宽
            worksheet8['!cols'] = [
                { wch: 10 },  // 第一列宽度
                { wch: 40 },   // 第二列宽度
                { wch: 40 }   // 第二列宽度
            ]
             // 5. 设置列宽
            worksheet9['!cols'] = [
                { wch: 10 },  // 第一列宽度
                { wch: 40 },   // 第二列宽度
                { wch: 40 }   // 第二列宽度
            ]
            // 3. 将工作表添加到工作簿
            XLSX.utils.book_append_sheet(workbook, worksheet, "设备");
            // XLSX.utils.book_append_sheet(workbook, worksheet7, "设备组代码表");
            // XLSX.utils.book_append_sheet(workbook, worksheet8, "设备模版代码表");
            // XLSX.utils.book_append_sheet(workbook, worksheet9, "设备子系列代码表");
            XLSX.utils.book_append_sheet(workbook, worksheet6, "通讯规约代码表");
            // 4. 生成 Excel 文件并下载
            const excelBuffer = XLSX.write(workbook, { bookType: "xlsx", type: "array" });
            const blob = new Blob([excelBuffer], { type: "application/octet-stream" });
            saveAs(blob, this.nowLeftRow.channel_name+"的设备信息.xlsx");
        },
        //导入设备信息
        daoruEXCELmoban(){
            this.$confirm(`导入设备会迁移覆盖，确定要导入吗？`,'提示',{
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
                this.$refs.EXCELinput.click();      
            }).catch(() => {
              // ...
            });
                    
        },
        //导入设备信息
        importTemplateEXCELinput(event){
            const file = event.target.files[0];
            if (!file) return;

            const reader = new FileReader();
            reader.onload = (e) => {
                const data = new Uint8Array(e.target.result);
                const workbook = XLSX.read(data, { type: 'array' });

                // 获取第一个工作表(串口)
                const firstSheetName = workbook.SheetNames[0];
                const worksheet = workbook.Sheets[firstSheetName];
                // 转换为 JSON
                var jsonData = XLSX.utils.sheet_to_json(worksheet, { defval: '' }).filter(item => item['设备名称'] && item['设备名称'] != '')

                // console.log("全部通道",jsonData);
                this.myjsonDataAll = jsonData
                // 存在相同的通道
                const duplicates = this.findAllDuplicateObjects(jsonData);
                // console.log("存在相同的通道",duplicates);
                this.repeatDataArea = duplicates
                if(duplicates.length != 0){
                  this.daorudiofalseEXCEL = true
                  this.$refs.EXCELinput.value = ""
                    return
                }
                this.chulihanshu()
                
                

               
                
                
            };
            reader.readAsArrayBuffer(file);
        },
        chulihanshu(){
            this.$refs.EXCELinput.value = ""
            this.daorudiofalseEXCEL= false
            var filterDataArea = this.filterUniqueByName(this.myjsonDataAll)
            var dd = []
            // console.log("filterDataArea",filterDataArea);
            filterDataArea.forEach((item,index) => {
                    dd.push({
                            "channel_number": Number(this.nowLeftRow.channel_number),
                            // "device_number": this.gudingchannel_number + index,
                            "device_name": String(item['设备名称']),
                            "device_address":item['设备地址'] == "" ? 0 : Number(item['设备地址']),
                            "device_addressex":item['扩展地址'] == "" ? '0' : String(item['扩展地址']),
                            // "device_group": item['设备组'] == "" ? 0 : Number(item['设备组']),
                            // "device_template": item['设备模版'] == "" ? 0 : Number(item['设备模版']),
                            // "device_serial_type": item['系列类型'] == "" ? 0 : Number(item['系列类型']),
                            "device_group": 0,
                            "device_template": 0,
                            "device_serial_type": 0,
                            "device_protocol":item['通讯协议'] == "" ? 0 : Number(item['通讯协议']),
                            "resend_count":item['重发次数'] == "" ? 3 : Number(item['重发次数']),
                            "break_count":item['中断次数'] == "" ? 1 : Number(item['中断次数']),
                            "run": item['是否投运'] == '是' ? 1 : 0,
                            "change": 0,
                    })
            })
             console.log("导入参数",dd);
                    if(dd.length == 0){
                      return
                    }
                    this.diaisMask = true
                    batchAddDevicechun(dd).then(res => {
                        this.diaisMask = false
                        if(res.code == 200){
                            this.addMord = false
                            this.getDeviceconfigidleNumberfn()
                            this.$message({showClose: true,message: '导入成功',type: 'success'});
                            this.getfindchannelconfigAll()
                        }else {
                            this.$message({showClose: true,message: '导入失败',type: 'error'});
                        }
                    })   
           
            
        },
        //找出数组对象名字属性相同的数据
        findAllDuplicateObjects(arr) {
                var typename = '设备名称'
                const nameCount = arr.reduce((acc, obj) => {
                    acc[obj[typename]] = (acc[obj[typename]] || 0) + 1;
                    return acc;
                }, {});
                return arr.filter(obj => nameCount[obj[typename]] > 1);
        },
        //过滤掉重复的数据
        filterUniqueByName(arr) {
                var typename = '设备名称'
                const seen = {};
                return arr.filter(item => {
                    const name = item[typename];
                    if (!seen[name]) {
                    seen[name] = true;
                    return true;
                    }
                    return false;
                });
        },

    },
};
</script>

<style lang="scss" scoped>
 .deviceediting {
    .leftandrightdialog2 {
        display: block !important;
        .leftname {
            display: flex;
            align-items: center;
            justify-content: space-between;
            width: 85px;
            min-width: 85px;
            text-align: left;
        }
    }
    .leftandrightdialog3 {
         .mytip {
             white-space: nowrap;
         }
         .myjia {
             margin: 0px 8px;
         }
         .leftname {
            text-align: right;
            display: block !important;
         }
    }
     .con {
        width: 100%;
        height: 100%;
        background-color: #fff;
        display: flex;
        position: relative;
        overflow: hidden;
        :deep(.leftdio .leftname){
            min-width: 90px;
        }
        .mytitle {
                 width: 100%;
                 height: 36px;
                 background-color: #F0F5FF;
                 border-radius: 4px;
                 display: flex;
                 align-items: center;
                 margin-top: 12px;
                 color: #000;
                //  font-weight: bold;
                 font-size: 15px;
                 .leftspan {
                    display: flex;
                    align-items: center;
                    span {
                         display: inline-block;
                     width: 3px;
                     height: 18px;
                     background-color: #2178F1;
                     margin-left: 12px;
                     margin-right: 6px;
                     border-radius: 3px;
                    }
                 }
        }
        .telescoping {
        position: absolute;
        left: 249px;
        top: 40px;
        width: 20px;
        height: 20px;
        border-radius: 50%;
        z-index: 10;
        border: 1px solid #ccc;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #fff;
        box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.2);
        transition: 0.3s;
        cursor: pointer;

        i {
          font-weight: 600;
          color: #666;
        }

        &.icon-active {
          left: 0px;
        }

        &:hover {
          background-color: #368ed9;

          i {
            color: #fff !important;
          }
        }
      }
        .left-tree {
             width: 260px;
             height: 100%;
             border-right: 1px solid #e6e6e6;
             padding: 12px;
             box-sizing: border-box;
             position: absolute;
            top: 0px;
            left: 0px;
            transition: 0.3s;

            &.left-tree-active {
            left: -260px;
            }
             .left-item {
                 width: 100%;
                 height: 48px;
                 border-radius: 4px;
                 font-size: 13px;
                 color: #666666;
                 display: flex;
                 align-items: center;
                 margin-bottom: 8px;
                 cursor: pointer;
                 span {
                    font-size: 15px;
                 }
                 img {
                     margin-left: 8px;
                     margin-right: 4px;
                 }
                 &.active {
                     background-color: #E7F0FF;
                     color: #2178F1;
                 }
             }
        }
        .right-con {
             width: calc(100% - 260px);
             height: 100%;
             box-sizing: border-box;
             transition: 0.3s;
             position: absolute;
            top: 0px;
            left: 268px;
            overflow: hidden;

            &.right-tab-active {
            width: 100%;
            left: 0px;
            }
             .top-search {
                 width: 100%;
                 //  height: 100px;
                 //  border-bottom: 1px solid #e6e6e6;
                 padding: 12px 12px 0px 12px;
                 box-sizing: border-box;
                //  margin-bottom: 12px;
                 :deep(.el-input__icon) {
                     line-height: 28px;
                 }
                 .search-item {
                     display: flex;
                     width: 100%;
                     height: 36px;
                     align-items: center;
                     .in-item {
                           display: flex;
                           align-items: center;
                           margin-right: 12px;
                           :deep(.el-input__inner) {
                             width: 1.4rem;
                             height: 28px !important;
                             line-height: 28px !important;
                           }
                     }
                     .item-name {
                         min-width: 48px;
                         text-align: right;
                         margin-right: 8px;
                         white-space: nowrap;
                         color: #333333;
                     }
                     .item-name2 {
                        min-width: 72px;
                     }
                 }
                 .ser-bo {
                     display: flex;
                     align-items: center;
                     justify-content: space-between;
                     margin-top: 6px;
                     .s-right {
                          display: flex;
                     align-items: center;
                     }
                 }
             }
             .mi-table {
                width: 100%;
                height: calc(100% - 170px);
                 padding: 12px 12px 16px 12px;
                 box-sizing: border-box;
                 border-bottom: 1px solid #e6e6e6;
                 .mysort {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                 }
                 :deep(.el-table__fixed-right) {
                         bottom: 9px !important;
                 }
                 :deep(.el-switch.is-checked .el-switch__core) {
                     width: 24px !important;
                     height: 12px;
                 }
                 :deep(.el-switch__core) {
                       width: 24px !important;
                     height: 12px;
                 }
                 :deep(.el-switch.is-checked .el-switch__core::after) {
                     margin-left: -10px;
                 }
                 :deep(.el-switch__core:after) {
                          top: 0px;
                          width: 10px;
                          height: 10px;
                 }
             }


        }
        .bot-btn {
            width: 100%;
            height: 60px;
            display: flex;
            padding: 0px 12px;
            align-items: center;
            box-sizing: border-box;
            .scr-div {
                 width: 100%;
                  height: 60px;
                display: flex;
                align-items: center;
                justify-content: space-between;
            }
        }
        .left-btn {
             display: flex;
             align-items: center;
        }
        .right-paging {
             position: relative;
             :deep(.el-pagination__sizes) {
                   
                    margin-right: 0px;
                    .el-input__inner {
                         border-radius: 4px !important;
                    }
                   
             }
             :deep(.el-pagination__total) {
                 color: #999999;
                 margin-right: 1px;
             }
             :deep(.el-pager) {
                    li {
                                margin: 0px 2px !important;
                            }
                   .number,.el-icon-more {
                      background-color: #fff;
                    border: 1px solid #E6E6E6;
                    box-sizing: border-box;
                      border-radius: 4px;
                   }
                    
             }
             :deep(.el-pagination.is-background .btn-next ){
                background-color: #fff;
                border: 1px solid #E6E6E6;
                box-sizing: border-box;
                border-radius: 4px;
                i {
                    color: #666666;
                }
             }
              
             :deep(.btn-next) {
                    margin-right: 106px;
             }
        }
     }
       .btn-item { 
                // width: 84px;
                padding: 0px 8px;
                box-sizing: border-box;
                height: 28px;
                display: flex;
                align-items: center;
                justify-content: center;
                border-radius: 4px;
                cursor: pointer;
                // box-sizing: border-box;
                img {
                     margin-left: 4px;
                }
             }
             .add-btn {
                 color: #fff;
                 background-color: #2178F1;
                 
             }
             .qi-btn {
                border: 1px solid #2178F1;
                color: #2178F1;
             }
             .del-btn {
                border: 1px solid #EE422B;
                color: #EE422B;
             }
             .quxiao {
                         margin-left: 8px;
                         color: #666666;
                         background-color: #fff;
                         border: 1px solid #cccccc;
                     }
    
 }
 .bottomoperate-btn {
                 width: 72px;
                 height: 28px;
                 display: flex;
                 align-items: center;
                 justify-content: center;
                 border-radius: 4px;
                 margin-right: 8px;
                 font-size: 12px;
                 cursor: pointer;
 }
.solidcolor {
     background-color: #2178F1;
     color: #fff;
 }
 .bordercolor {
                 border: 1px solid #2178F1;
                 background-color: #E7F0FF;
                 color: #2178F1;
                 box-sizing: border-box;
}
 .drawer-con {
      width: 100%;
      height: 100%;
       .drawer-top {
          width: 100%;
          height: 52px;
          padding: 20px 20px 0px 20px;
          box-sizing: border-box;
          border-bottom: 1px solid #EBEBEB;
          display: flex;
          justify-content: space-between;
          span {
             color: #1A1A1A;
             font-size: 16px;
          }
          i {
             font-size: 20px !important;
             position: relative;
             top: 2px;
              cursor: pointer;
          }
       }
       .drawer-middle {
          width: 100%;
          height: calc(100% - 116px);
          padding: 20px;
          box-sizing: border-box;
       }
       .drawer-bottom {
         width: 100%;
         height: 64px;
         border-top: 1px solid #E0EDFF;
         padding-top: 12px;
         box-sizing: border-box;
         display: flex;
         justify-content: center;
       }
    }
.input-item {
     display: flex;
     align-items: center;
     width: 100%;
     height: 44px;
     .leftname {
         width: 72px;
         text-align: right;
         font-size: 12px;
         color: #666666;
         margin-right: 8px;
         span {
             color: #FF0000;
             margin-right: 1px;
         }
     }
     :deep(.el-input__inner){
         height: 28px;
         line-height: 28px;
     }
     .tips {
          font-size: 12px;
          color: #666666;
          margin-left: 8px;
     }
     

}
.choicedio .items .leftname {
     width: 90px !important;
     min-width: 90px !important;
}
</style>